package com.mycompany.webantons;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 * This Managed Bean provides a possibility for the userto log out of the webapp
 * 
 */
@Named(value = "logoutBean")
@RequestScoped
public class LogoutBean {
    
    // used for system messaging
    private static Logger logger = Logger.getLogger(LogoutBean.class.getName());

    
    // logout method
    public String logout() {
        
        String target = "/index?faces-redirect=true";// this if logout sucess

       // facescontext has all information about per request state of a single request
        FacesContext context = FacesContext.getCurrentInstance();
        
        HttpServletRequest request = 
                (HttpServletRequest) context.getExternalContext().getRequest();

        try {
            request.logout();// request for logout
        } catch (ServletException e) {
            logger.log(Level.SEVERE, "Utloggningen misslyckades!", e);
            target = "/loginerror?faces-redirect=true";// this if logout unsucessfull
        }

        return target; // 
    }
}
